<template>
  <view :class="['add-giftbook-container', `theme-${currentTheme}`]">
    <form @submit="handleSubmit">
      <!-- 基本信息 -->
      <view class="form-section">
        <view class="section-title">基本信息</view>
        
        <view class="form-item">
          <text class="label">礼簿标题</text>
          <input 
            class="input" 
            v-model="formData.title" 
            placeholder="请输入礼簿标题"
            placeholder-class="placeholder"
          />
        </view>

        <view class="form-item">
          <text class="label">礼簿类型</text>
          <picker 
            :value="currentTypeIndex" 
            :range="typeOptions" 
            range-key="label"
            @change="onTypeChange"
          >
            <view class="picker-content">
              <text>{{ typeOptions[currentTypeIndex].label }}</text>
              <uni-icons type="bottom" size="14" color="#666666" />
            </view>
          </picker>
        </view>

        <view class="form-item">
          <text class="label">日期</text>
          <picker 
            mode="date" 
            :value="formatDate(formData.date)" 
            @change="onDateChange"
          >
            <view class="picker-content">
              <text>{{ formatDate(formData.date) }}</text>
              <uni-icons type="bottom" size="14" color="#666666" />
            </view>
          </picker>
        </view>

        <view class="form-item">
          <text class="label">地点</text>
          <input 
            class="input" 
            v-model="formData.location" 
            placeholder="请输入地点（选填）"
            placeholder-class="placeholder"
          />
        </view>

        <view class="form-item">
          <text class="label">描述</text>
          <textarea 
            class="textarea" 
            v-model="formData.description" 
            placeholder="请输入描述（选填）"
            placeholder-class="placeholder"
          />
        </view>
      </view>

      <!-- 提交按钮 -->
      <view class="submit-section">
        <view class="button-wrapper">
          <button 
            form-type="submit"
            :disabled="!isValid"
            class="custom-button custom-button--large custom-button--round custom-button--block"
            :class="{ 'custom-button--disabled': !isValid }"
          >
            创建礼簿
          </button>
        </view>
      </view>
    </form>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useGiftBookStore } from '@/store/modules/giftbook';
import { useThemeStore, ThemeType } from '@/store/modules/theme';
import useThemeMixin from '@/mixins/themeMixin';
import { GiftBookType } from '@/types/giftbook';

const giftBookStore = useGiftBookStore();
const themeStore = useThemeStore();

// 当前主题
const currentTheme = computed(() => themeStore.currentTheme);

// 使用主题mixin
useThemeMixin();

// 表单数据
const formData = ref({
  title: '',
  type: GiftBookType.WEDDING, // 设置默认类型
  date: new Date().toISOString().split('T')[0], // 设置默认日期为今天
  location: '',
  description: '',
});

// 格式化日期
const formatDate = (timestamp: number | string): string => {
  if (typeof timestamp === 'number') {
    return new Date(timestamp).toISOString().split('T')[0];
  }
  return timestamp;
};

// 类型选项
const typeOptions = [
  { value: GiftBookType.WEDDING, label: '婚礼礼簿' },
  { value: GiftBookType.FUNERAL, label: '白事礼簿' },
  { value: GiftBookType.BIRTHDAY, label: '生日礼簿' },
  { value: GiftBookType.GRADUATION, label: '升学礼簿' },
  { value: GiftBookType.BUSINESS, label: '商务礼簿' },
  { value: GiftBookType.HOUSEWARMING, label: '乔迁礼簿' },
  { value: GiftBookType.FULLMOON, label: '满月礼簿' },
  { value: GiftBookType.OTHER, label: '其他礼簿' }
];

// 根据当前主题设置默认类型
const currentTypeIndex = ref(typeOptions.findIndex(
  type => type.value === themeStore.currentTheme
) || 0);

// 当前选中的类型
const currentType = computed(() => typeOptions[currentTypeIndex.value].value);

// 表单验证
const isValid = computed(() => {
  return formData.value.title && formData.value.type && formData.value.date;
});

// 根据主题自动选择类型
const autoSelectTypeByTheme = () => {
  switch (currentTheme.value) {
    case ThemeType.FUNERAL:
      formData.value.type = GiftBookType.FUNERAL;
      break;
    case ThemeType.WEDDING:
      formData.value.type = GiftBookType.WEDDING;
      break;
    case ThemeType.BIRTHDAY:
      formData.value.type = GiftBookType.BIRTHDAY;
      break;
    case ThemeType.GRADUATION:
      formData.value.type = GiftBookType.GRADUATION;
      break;
    case ThemeType.BUSINESS:
      formData.value.type = GiftBookType.BUSINESS;
      break;
    case ThemeType.HOUSEWARMING:
      formData.value.type = GiftBookType.HOUSEWARMING;
      break;
    case ThemeType.FULLMOON:
      formData.value.type = GiftBookType.FULLMOON;
      break;
    default:
      formData.value.type = GiftBookType.OTHER;
  }
};

// 在组件挂载时自动选择类型
onMounted(() => {
  autoSelectTypeByTheme();
});

// 类型变更处理
const onTypeChange = (e: any) => {
  currentTypeIndex.value = e.detail.value;
  formData.value.type = typeOptions[currentTypeIndex.value].value;
  // 更新主题但不立即更新 tabBar
  themeStore.setTheme(currentType.value, false);
};

// 日期变更处理
const onDateChange = (e: any) => {
  formData.value.date = e.detail.value;
};

// 提交表单
const handleSubmit = async () => {
  console.log('表单提交事件触发');
  console.log('表单数据:', formData.value);
  
  if (!isValid.value) {
    console.log('表单验证失败', {
      title: formData.value.title,
      type: formData.value.type,
      date: formData.value.date
    });
    
    uni.showToast({
      title: '请填写必要信息',
      icon: 'none',
      duration: 2000
    });
    return;
  }

  try {
    const timestamp = Date.now();
    const giftBook = {
      id: `giftbook_${timestamp}`,
      title: formData.value.title.trim(),
      type: formData.value.type,
      date: formData.value.date,
      location: formData.value.location?.trim() || '',
      description: formData.value.description?.trim() || '',
      records: [],
      totalAmount: 0,
      createTime: timestamp,
      updateTime: timestamp
    };

    console.log('准备添加礼簿:', giftBook);
    await giftBookStore.addGiftBook(giftBook);

    uni.showToast({
      title: '创建成功',
      icon: 'success',
      duration: 1500
    });

    // 使用 switchTab 跳转到 tabBar 页面
    setTimeout(() => {
      uni.switchTab({
        url: '/pages/giftbook/index',
        success: () => {
          console.log('跳转成功');
        },
        fail: (error) => {
          console.error('跳转失败', error);
          // 如果 switchTab 失败，尝试使用 navigateBack
          uni.navigateBack({
            delta: 1
          });
        }
      });
    }, 1500);
  } catch (error) {
    console.error('创建礼簿失败', error);
    uni.showToast({
      title: '创建失败，请重试',
      icon: 'error',
      duration: 2000
    });
  }
};
</script>

<style lang="scss">
.add-giftbook-container {
  min-height: 100vh;
  padding: 32rpx;

  .form-section {
    background: #fff;
    border-radius: 16rpx;
    padding: 32rpx;
    margin-bottom: 32rpx;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);

    .section-title {
      font-size: 32rpx;
      font-weight: bold;
      color: var(--text-primary);
      margin-bottom: 32rpx;
    }
  }

  .form-item {
    margin-bottom: 32rpx;

    .label {
      display: block;
      font-size: 28rpx;
      color: var(--text-secondary);
      margin-bottom: 16rpx;
    }

    .input, .textarea {
      width: 100%;
      border: 2rpx solid var(--border-color);
      border-radius: 8rpx;
      padding: 16rpx;
      font-size: 28rpx;
      color: var(--text-primary);
      background-color: #fff;
      transition: all 0.3s ease;

      &:focus {
        border-color: var(--button-color);
        box-shadow: 0 0 0 2rpx rgb(var(--button-color-rgb) / 0.1);
      }
    }

    .textarea {
      height: 160rpx;
    }

    .picker-content {
      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 100%;
      border: 2rpx solid var(--border-color);
      border-radius: 8rpx;
      padding: 16rpx;
      font-size: 28rpx;
      color: var(--text-primary);
      background-color: #fff;
      transition: all 0.3s ease;

      &:active {
        border-color: var(--button-color);
        background-color: rgb(var(--button-color-rgb) / 0.05);
      }
    }
  }

  .submit-section {
    margin-top: 64rpx;
    padding: 0 32rpx;

    .button-wrapper {
      position: relative;
      width: 100%;
      
      &::after {
        content: '';
        position: absolute;
        left: 0;
        right: 0;
        bottom: -16rpx;
        height: 32rpx;
        background: linear-gradient(
          to bottom, 
          rgb(var(--button-color-rgb) / 0.2),
          rgb(var(--button-color-rgb) / 0)
        );
        filter: blur(8rpx);
        border-radius: 50%;
        opacity: 0.5;
        z-index: -1;
      }
    }
  }

  .placeholder {
    color: var(--text-secondary);
  }
}
</style> 